package com.lwl.blog.controller;

import com.lwl.blog.core.servlet.BaseServlet;
import com.lwl.blog.entity.UserEntity;
import com.lwl.blog.service.UserService;
import com.lwl.blog.service.impl.UserServiceImpl;
import org.apache.commons.io.IOUtils;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Part;
import java.io.FileInputStream;
import java.io.IOException;
@MultipartConfig
@WebServlet("/FileServlet/*")
public class FileServlet extends BaseServlet {
    private UserService u=new UserServiceImpl();

    public String upload() throws Exception{
        //1.获得前端接受的文件
//        Part p=req.getParameter("pngFile");
        Part p=req.getPart("pngFile");
        System.out.println(p);
        //2.获取文件的名称，上传位置，路径
        String submittedFileName = p.getSubmittedFileName();
        String realPath = req.getServletContext().getRealPath( "jpg");
        String filePath =realPath+"\\"+submittedFileName;
        //3.写入指定路径
        p.write(filePath );
        //4.更新用户头像
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        u.updateHeaderUrl(loginUser.getId(),filePath );
        //5.响应
        return outJson(true);
    }

    public void showPng() throws IOException {
        //1.获取前端数据
        String url=req.getParameter("fileName");
        String real = req.getServletContext().getRealPath( "jpg");
        //2.输入流输入
        FileInputStream ips=new FileInputStream(real+"//"+url);
        //io流拷贝，将输入流对象中的内容拷贝到ops中？
        IOUtils.copy(ips,resp.getOutputStream());
    }

}
